import json
import os
import time
from functools import wraps

import jwt
from flask import Blueprint
from flask import jsonify, request, abort, make_response, render_template

from tools.log.logU import logU
from tools.conf.confU import confU

from service.service import MyService

# 创建一个Blueprint的实例
myApi = Blueprint('myApi', __name__)
cfgdir = os.path.split(os.path.realpath(__file__))[0]
paths = cfgdir.split("/")
a = len(paths) - 1
separator = '/'
arr = paths[1:a]
b = '/' + separator.join(arr) + '/'
log = logU(cfg=b)


def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            if auth_header.startswith('Bearer '):
                token = auth_header.split(" ")[1]  # 分割"Bearer "和token

        if not token:
            return jsonify({'message': 'Token is missing!'}), 403
        try:
            data = jwt.decode(token, confU.config.get('encrypt', 'SECRET_KEY'), algorithms=["HS256"])
            print(data)
            exp = int(data.pop("exp"))
            if time.time() > exp:
                return jsonify({'message': ''})
            elif time.time() > (exp - 3600 * 12 * 3):
                return jsonify({'message': ''})
            else:
                return jsonify({'message': ''})

        except:
            return jsonify({'message': 'Token is invalid!'}), 403
        finally:
            print()
        return f(*args, **kwargs)

    return decorated


@myApi.before_request
def before_request():
    # 在这里可以访问request的属性和方法
    log.logger.info(request.method)
    log.logger.info(request.path)
    log.logger.info(request.data)

    # logger.info(f"收到请求{ json.dumps(request.data)}")
    # 可以修改request的数据
    # 例如: request.data = "new data"


@myApi.after_request
def after_request(response):
    # 在这里可以访问和修改响应对象response
    response.headers['Custom-Header'] = 'Custom Value'
    response.headers['Content-Type'] = 'application/json'
    # 返回响应对象response
    log.logger.info(f"返回{response.data}{response.headers}")
    return response


@myApi.errorhandler(404)
def error(error):
    return render_template('404.html')


@myApi.route('/m', methods=["POST"])
def index():
    return jsonify({'message': 'Hello from my_api!'})


@myApi.route('/getCorrData', methods=["POST"])
def get_corr_data():
    s = MyService(cfg='')
    s.get_corr_data(code='600487')
    if request.json is not None:
        print(request.json)
    return jsonify({'msg': 'Hello', 'code': '000'})
